package com.shlh.saas.util;

import org.springframework.core.io.Resource;
import org.springframework.core.io.UrlResource;
import org.springframework.web.multipart.MultipartFile;

import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.net.MalformedURLException;
import java.nio.file.Files;
import java.nio.file.Path;

/**
 * 自定义MultipartFile实现类，用于将本地文件转换为MultipartFile
 */
public class CustomMultipartFile implements MultipartFile {

    private final File file;
    private final String name;
    private final String originalFilename;
    private final String contentType;
    private final byte[] content;

    public CustomMultipartFile(File file) throws IOException {
        this.file = file;
        this.name = file.getName();
        this.originalFilename = file.getName();
        this.contentType = Files.probeContentType(file.toPath());
        this.content = Files.readAllBytes(file.toPath());
    }

    public CustomMultipartFile(File file, String name) throws IOException {
        this.file = file;
        this.name = name;
        this.originalFilename = file.getName();
        this.contentType = Files.probeContentType(file.toPath());
        this.content = Files.readAllBytes(file.toPath());
    }

    public CustomMultipartFile(File file, String name, String originalFilename) throws IOException {
        this.file = file;
        this.name = name;
        this.originalFilename = originalFilename;
        this.contentType = Files.probeContentType(file.toPath());
        this.content = Files.readAllBytes(file.toPath());
    }

    @Override
    public String getName() {
        return name;
    }

    @Override
    public String getOriginalFilename() {
        return originalFilename;
    }

    @Override
    public String getContentType() {
        return contentType;
    }

    @Override
    public boolean isEmpty() {
        return content.length == 0;
    }

    @Override
    public long getSize() {
        return content.length;
    }

    @Override
    public byte[] getBytes() throws IOException {
        return content;
    }

    @Override
    public InputStream getInputStream() throws IOException {
        return new ByteArrayInputStream(content);
    }

    @Override
    public Resource getResource() {
        try {
            return new UrlResource(file.toURI());
        } catch (MalformedURLException e) {
            throw new RuntimeException("Failed to get resource for file: " + file.getAbsolutePath(), e);
        }
    }

    @Override
    public void transferTo(File dest) throws IOException, IllegalStateException {
        Files.write(dest.toPath(), content);
    }

    @Override
    public void transferTo(Path dest) throws IOException, IllegalStateException {
        Files.write(dest, content);
    }
} 